﻿using System;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Text;
using System.Web;
using Framework;

namespace Enterprise
{
    public class DownloadService : BaseService
    {
        /// <summary>
        /// 添加下载资源
        /// </summary>
        /// <param name="name"></param>
        /// <param name="nameEn"></param>
        /// <param name="description"></param>
        /// <param name="descriptionEn"></param>
        /// <param name="type"> </param>
        /// <param name="language"> </param>
        /// <param name="sort"> </param>
        /// <param name="filedata"> </param>
        /// <returns></returns>
        public int Add(string name, string nameEn, string description, string descriptionEn, int type, string language, int sort, HttpPostedFileBase filedata)
        {
            Check.Argument.IsNotOutOfLength(name, 50, "资源名称");
            Check.Argument.IsNotOutOfLength(nameEn, 50, "资源名称(En)");
            var ext = Path.GetExtension(filedata.FileName);
            var uploadHelper = new UploadHelper
            {
                PostedFile = filedata,
                RelativePath = DownloadConfig.RelativePath,
                IsImage = false,
                FileMaxLength = DownloadConfig.FileSize,
                UploadFileType = UploadHelper.UploadFileTypeEnum.File
            };
            if (!uploadHelper.Save())
            {
                throw new Exception(uploadHelper.ErrorMessage);
            }
            var filePath = uploadHelper.FilePhyPath;
            var fileName = uploadHelper.FileName;
            var sb = new StringBuilder();
            sb.Append("insert into TbDownload(");
            sb.Append("CoName,CoType,CoTypeName,CoUrl,CoDate,CoDescription,CoLanguage,CoNameEn,CoDescriptionEn,CoTypeNameEn,CoFileName,CoPath,CoSort");
            sb.Append(") values(");
            sb.Append("@CoName,@CoType,@CoTypeName,@CoUrl,@CoDate,@CoDescription,@CoLanguage,@CoNameEn,@CoDescriptionEn,@CoTypeNameEn,@CoFileName,@CoPath,@CoSort");
            sb.Append(")");
            var parameter = new[]
                                {
                                    new OleDbParameter("@CoName", OleDbType.VarChar, 255),
                                    new OleDbParameter("@CoType", OleDbType.VarChar, 50),
                                    new OleDbParameter("@CoTypeName", OleDbType.VarChar, 255),
                                    new OleDbParameter("@CoUrl", OleDbType.VarChar, 255),
                                    new OleDbParameter("@CoDate", OleDbType.Date),
                                    new OleDbParameter("@CoDescription", OleDbType.LongVarWChar),
                                    new OleDbParameter("@CoLanguage", OleDbType.VarChar, 10),
                                    new OleDbParameter("@CoNameEn", OleDbType.VarChar, 255),
                                    new OleDbParameter("@CoDescriptionEn", OleDbType.LongVarWChar),
                                    new OleDbParameter("@CoTypeNameEn", OleDbType.VarChar, 255),
                                    new OleDbParameter("@CoFileName", OleDbType.VarChar, 255),
                                    new OleDbParameter("@CoPath", OleDbType.VarChar, 255),
                                    new OleDbParameter("@CoSort", OleDbType.Integer),
                                    new OleDbParameter("@CoExtensionName", OleDbType.VarChar, 20)

                                };
            parameter[0].Value = name;
            parameter[1].Value = type;
            parameter[2].Value = "";
            parameter[3].Value = "";
            parameter[4].Value = DateTime.Now;
            parameter[5].Value = description;
            parameter[6].Value = language;
            parameter[7].Value = nameEn;
            parameter[8].Value = descriptionEn;
            parameter[9].Value = "";
            parameter[10].Value = fileName;
            parameter[11].Value = filePath;
            parameter[12].Value = sort;
            parameter[13].Value = ext;
            var rows = DbHelperOleDb.Add(sb.ToString(), parameter).SafeToInt();
            if (rows > 0)
            {
                return rows;
            }
            throw new Exception("添加失败！");
        }
        public int Eidt(int id, string name, string nameEn, string description, string descriptionEn, int type, string language, int sort)
        {
            Check.Argument.IsNotOutOfLength(name, 50, "图片名称");
            Check.Argument.IsNotOutOfLength(nameEn, 50, "图片名称(En)");
            var sbSql = new StringBuilder();
            sbSql.Append("update TbDownload set ");
            sbSql.Append(" CoName=@CoName,");
            sbSql.Append(" CoDescription=@CoDescription,");
            sbSql.Append(" CoLanguage=@CoLanguage,");
            sbSql.Append(" CoNameEn=@CoNameEn,");
            sbSql.Append(" CoDescriptionEn=@CoDescriptionEn,");
            sbSql.Append(" CoType=@CoType,");
            sbSql.Append(" CoTypeName=@CoTypeName,");
            sbSql.Append(" CoTypeNameEn=@CoTypeNameEn,");
            sbSql.Append(" CoSort=@CoSort");
            sbSql.AppendFormat(" where CoDownloadId={0}", id);
            var parameter = new[]
                {
                    new OleDbParameter("@CoName", OleDbType.VarChar, 255),
                    new OleDbParameter("@CoDescription", OleDbType.LongVarWChar),
                    new OleDbParameter("@CoLanguage", OleDbType.VarChar, 10),
                    new OleDbParameter("@CoNameEn", OleDbType.VarChar, 255),
                    new OleDbParameter("@CoDescriptionEn", OleDbType.LongVarWChar),
                    new OleDbParameter("@CoType", OleDbType.Integer),
                    new OleDbParameter("@CoTypeName", OleDbType.VarChar, 255),
                    new OleDbParameter("@CoTypeNameEn", OleDbType.VarChar, 255),
                    new OleDbParameter("@CoSort", OleDbType.Integer)
                };
            parameter[0].Value = name;
            parameter[1].Value = description;
            parameter[2].Value = language;
            parameter[3].Value = nameEn;
            parameter[4].Value = descriptionEn;
            parameter[5].Value = type;
            parameter[6].Value = "";
            parameter[7].Value = "";
            parameter[8].Value = sort;
            var rows = DbHelperOleDb.ExecuteSql(sbSql.ToString(), parameter).SafeToInt();
            if (rows > 0)
            {
                return rows;
            }
            throw new Exception("修改失败！");
        }


        public void Delete(int id)
        {
            var path = HttpContext.Current.Server.MapPath(DownloadConfig.RelativePath);
            var ds = DbHelperOleDb.Query("select * from TbDownload where CoDownloadId={0}".FormatWith(id));
            foreach (DataRow item in ds.Tables["ds"].Rows)
            {
                FileHelper.DeleteSub(Path.Combine(path, item["CoFileName"].SafeToString()));
            }
            int rows = DbHelperOleDb.ExecuteSql("delete from TbDownload where CoDownloadId={0}".FormatWith(id));
            if (!(rows > 0))
                throw new Exception("记录不存在！");
        }
        public int DeletePicture(int id)
        {
            var path = HttpContext.Current.Server.MapPath(DownloadConfig.RelativePath);
            var ds = DbHelperOleDb.Query("select * from TbDownload where CoDownloadId={0}".FormatWith(id));
            foreach (DataRow item in ds.Tables["ds"].Rows)
            {
                FileHelper.DeleteSub(Path.Combine(path, item["CoFileName"].SafeToString()));
            }
            int rows = DbHelperOleDb.ExecuteSql("update TbDownload set CoFileName='' where CoDownloadId={0}".FormatWith(id));
            return rows;
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <returns>Table 返回一张表格</returns>
        public Table GetTable(string name, string lanuage, int pageValue, int rowsValue, string sort = "cosort", string order = "desc")
        {
            var sbSqlWhere = new StringBuilder();
            sbSqlWhere.Append(" where (CoName like '%'+@CoName+'%' or  CoNameEn like '%'+@CoName+'%') and CoLanguage like '%'+@CoLanguage+'%'");
            var parameter = new[]
                {
                    new OleDbParameter("@CoName", OleDbType.VarChar, 255),
                     new OleDbParameter("@CoLanguage", OleDbType.VarChar, 255)
                };
            parameter[0].Value = name.SqlLike();
            parameter[1].Value = lanuage;
            int total = DbHelperOleDb.GetSingle("select count(*) from TbDownload {0}".FormatWith(sbSqlWhere), parameter).SafeToInt();
            var sbSql = new StringBuilder();
            sbSql.Clear();
            sbSql.AppendFormat("select top {0} * from TbDownload {1} ", rowsValue, sbSqlWhere);
            if (pageValue > 1)
                sbSql.AppendFormat(" and CoDownloadId not in (select top {0} CoDownloadId from TbDownload {1} order by {2} {3},CoDownloadId desc) ", rowsValue * (pageValue - 1), sbSqlWhere, sort, order);
            sbSql.AppendFormat(" order by {0} {1},CoDownloadId desc ", sort, order);
            var ds = DbHelperOleDb.Query(sbSql.ToString(), parameter);
            var table = new Table
            {
                Rows = ds.Tables["ds"].Rows,
                Total = total
            };
            return table;
        }
        /// <summary>
        /// 根据ID获取一条记录
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public DataRow GetById(int id)
        {
            return DbHelperOleDb.Query("select * from TbDownload where CoDownloadId={0}".FormatWith(id)).Tables["ds"].Rows[0];
        }
    }
}